package com.sailing.xjpb.web.base.bean.processor;

import com.sailing.xjpb.common.encrypt.PasswordDecodeHandler;
import com.sailing.xjpb.web.base.bean.configuration.DecodeConfigProperties;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;

import java.util.Collection;
import java.util.Optional;


/**
 * 数据源类加载 后置处理器
 *
 * @author sutao
 * createDate 2022/10/15 17:13
 */
@Slf4j
public class DataSourceBeanPostProcessor implements BeanPostProcessor {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private DecodeConfigProperties decodeConfigProperties;

    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
        Optional<PasswordDecodeHandler> opt = getHandler(bean);
        String decodeKey = decodeConfigProperties.getKey();
        if (opt.isPresent()) {
            PasswordDecodeHandler passwordDecodeHandler = opt.get();
            passwordDecodeHandler.decode(decodeKey, bean);
        }
        return bean;
    }

    /**
     * @param bean 容器中类的实例对象
     * @return Optional
     * @author sutao
     * createDate 2022/10/16 16:32
     * <p>
     * editDescription:
     * editUser sutao
     * editDate 2022/10/16 16:32
     */
    private Optional<PasswordDecodeHandler> getHandler(Object bean) {
        Collection<PasswordDecodeHandler> handlers =
                applicationContext.getBeansOfType(PasswordDecodeHandler.class).values();
        return handlers.stream().filter(e -> e.isSupported(bean)).findFirst();
    }

}
